/**
 * EnhancedPageLoadTimer —— 页面加载时间记录 + 图标＋颜色阈值展示（工具函数形式）
 *
 * 行业规范（可自定义）：
 *   ≤ 2000ms: 优秀 (😁 绿色)
 *   ≤ 4000ms: 良好 (🙂 蓝色)
 *   ≤ 7000ms: 警告 (😐 橙色)
 *   >  7000ms: 糟糕 (😡 红色)
 *
 * 用法：
 *   <script src="enhanced-page-load-timer.js"></script>
 *   <!-- 手动初始化自动埋点 -->
 *   <script>EnhancedPageLoadTimer.init();</script>
 *
 *   // 手动测量示例：
 *   EnhancedPageLoadTimer.start('MyTask');
 *   // … 执行任务 …
 *   EnhancedPageLoadTimer.end('MyTask');
 */

// 默认标签和阈值配置
const DEFAULT_LABEL = "Page Load";
const DEFAULT_THRESHOLDS = [
  { max: 2000, label: "优秀", icon: "✅", color: "#7CFC00" }, // LawnGreen
  { max: 4000, label: "良好", icon: "👍", color: "#00FFFF" }, // Aqua
  { max: 7000, label: "警告", icon: "⚠️", color: "#FFD700" }, // Gold
  { max: Infinity, label: "糟糕", icon: "❌", color: "#FF4500" } // OrangeRed
];

// 用于存放各计时器的开始时间
const timers = new Map();

/**
 * 启动计时
 * @param {string} [label=DEFAULT_LABEL] - 计时标签
 */
export function start(label = DEFAULT_LABEL) {
  timers.set(label, performance.now());
}

/**
 * 停止计时并输出结果
 * @param {string} [label=DEFAULT_LABEL] - 与 start 对应的计时标签
 */
export function end(label = DEFAULT_LABEL) {
  const t0 = timers.get(label);
  if (t0 == null) {
    console.warn(`🔍 [EnhancedPageLoadTimer] 未找到 "${label}" 的 start 时刻`);
    return;
  }
  const duration = performance.now() - t0;
  timers.delete(label);
  _displayConsole(label, duration);
  // if (label === DEFAULT_LABEL) {
  //   _displayOverlay(duration);
  // }
}

/**
 * 控制台彩色输出
 */
function _displayConsole(label, ms) {
  const { color, icon, label: level } = _getThreshold(ms);
  console.log(
    `%c${icon}%c [${label}] %c${level}%c： %c${ms.toFixed(2)}ms`,
    `color:${color}; font-size:16px;`, // 图标
    "", // 恢复默认
    `color:${color}; font-style:italic;`, // 性能等级
    "", // 恢复默认
    `color:${color}; font-family:monospace;` // 耗时数字
  );
}

/**
 * 页面右上角浮层显示
 */
function _displayOverlay(ms) {
  const { color, icon, label: level } = _getThreshold(ms);
  if (document.getElementById("_pltimer_overlay")) return;
  const div = document.createElement("div");
  div.id = "_pltimer_overlay";
  div.innerText = `${icon} ${level}：${ms.toFixed(0)}ms`;
  Object.assign(div.style, {
    position: "fixed",
    top: "16px",
    right: "16px",
    padding: "8px 12px",
    background: "rgba(255,255,255,0.9)",
    color,
    fontWeight: "bold",
    fontFamily: "sans-serif",
    borderRadius: "4px",
    boxShadow: "0 2px 6px rgba(0,0,0,0.2)",
    transition: "opacity 0.3s ease, transform 0.3s ease",
    transform: "translateY(-10px)",
    opacity: "0"
  });
  document.body.appendChild(div);
  // 触发入场动画
  requestAnimationFrame(() => {
    div.style.transform = "translateY(0)";
    div.style.opacity = "1";
  });
  // 3s 后自动消失
  setTimeout(() => {
    div.style.opacity = "0";
    div.style.transform = "translateY(-10px)";
    setTimeout(() => div.remove(), 300);
  }, 3000);
}

/**
 * 根据耗时获取对应阈值配置
 */
function _getThreshold(ms) {
  return DEFAULT_THRESHOLDS.find(t => ms <= t.max);
}
